package com.huqing.icu.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * 复制bean的工具类
 */
public class CopyUtils {

    private static final Logger logger = LoggerFactory.getLogger(CopyUtils.class);

    public static void copy(Object dest, Object orig) {
        try {
            BeanUtils.copyProperties(dest, orig);
        } catch (IllegalAccessException | InvocationTargetException e) {
            logger.error("[CopyUtils] copy error", e);
        }
    }



    /**
     * 将origin对象拷贝到dest对象
     *
     * @param orig    原始对象
     * @param destClass 目标对象的类型
     * @return 目标类对象
     */
    public static <T> T copy(Object orig, Class<T> destClass) {
        if (orig != null) {
            try {
                T t = destClass.newInstance();
                copy(t, orig);
                return t;
            } catch (InstantiationException | IllegalAccessException | BeansException e) {
            }
        }
        return null;
    }

    /**
     * 将origin类的List映射为dest类的List
     * @param originList 原始类列表
     * @param destClass 目标类class
     */
    public static <K, T> List<K> copyOriginListToDestList(List<T> originList, Class<K> destClass) {
        int size = originList.size();
        List<K> destList = new ArrayList<K>(size);
        for(int i = 0; i < size; ++i) {
            K k;
            try {
                k = destClass.newInstance();
                copy(k, originList.get(i));
                destList.add(k);
            } catch (InstantiationException | IllegalAccessException e) {
                //
            }
        }

        return destList;
    }
}
